package com.lizemin.springaspect.interceptor;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author lzm
 * @date 2025/3/31 19:12
 * @description
 */
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 获取请求体中的内容
        RepeatableRequestWrapper requestWrapper = (RepeatableRequestWrapper) request;
        String requestBody = requestWrapper.getRequestBody();
        log.info("本次请求的请求体为：{}", requestBody);
        Map<String, String[]> parameterMap = requestWrapper.getParameterMap();
        log.info("请求参数为：{}", JSONUtil.toJsonStr(parameterMap));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RepeatableResponseWrapper responseWrapper = (RepeatableResponseWrapper) response;
        String responseBody = responseWrapper.getResponseBody();
        log.info("本次请求返回的响应体为：{}", responseBody);
    }

}
